package com.ljkj.cordial.chat.util;

import android.app.Activity;
import android.content.Context;

import com.ljkj.cordial.chat.bean.ChatTableUnit;
import com.ljkj.cordial.chat.bean.MsgType;
import com.ljkj.cordial.chat.dao.ChatTableBean;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ReadFinishTask implements Runnable {
    private ScheduledExecutorService exec;
    private Context cxt;
    private List<ChatTableUnit> datas;
    private volatile boolean isStartAnnexReadFinish;
    private volatile boolean isPause;

    public void setPause(boolean pause) {
        isPause = pause;
    }

    public void setStartAnnexReadFinish(boolean startAnnexReadFinish) {
        isStartAnnexReadFinish = startAnnexReadFinish;
    }

    public ReadFinishTask(Context cxt) {
        this.cxt = cxt;
    }


    public void start(List<ChatTableUnit> datas) {
        this.datas = datas;
        if (exec == null || exec.isShutdown()) {
            exec = Executors.newSingleThreadScheduledExecutor();
            exec.scheduleAtFixedRate(this, 1, 1, TimeUnit.SECONDS);
        }
    }


    @Override
    public void run() {
        if (isPause) {
            return;
        }
        if (datas != null && !datas.isEmpty()) {
            boolean isEmptyTask = true;
            for (int i = 0; i < datas.size(); i++) {
                ChatTableUnit d = datas.get(i);
                if (d.isStartReadFinish() && d.getSendState() == ChatTableUnit.SEND_SUCCESS) {
                    if (d.getReadFinishSpaceTime() > 0L) {
                        isEmptyTask = false;
                        if (onReadFinishUpdateListener != null) {
                            if (!((Activity) cxt).isFinishing() && onReadFinishUpdateListener != null) {
                                int finalI = i;
                                ((Activity) cxt).runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            onReadFinishUpdateListener.onUpdate(finalI);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            }
                        }
                    } else {
                        ChatTableBean.delete(ChatTableUnit.getTable(d));
                        if (!((Activity) cxt).isFinishing() && onReadFinishComplete != null) {
                            int finalI = i;
                            ((Activity) cxt).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        onReadFinishComplete.onComplete(finalI);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }

                    }
                }

            }
            if (isEmptyTask || ((Activity) cxt).isFinishing()) {
                exec.shutdownNow();
            }
        }
    }

    public OnReadFinishComplete onReadFinishComplete;

    public ReadFinishTask setOnReadFinishComplete(OnReadFinishComplete onReadFinishComplete) {
        this.onReadFinishComplete = onReadFinishComplete;
        return this;
    }

    public interface OnReadFinishComplete {
        void onComplete(int position);
    }

    private OnReadFinishUpdateListener onReadFinishUpdateListener;

    public ReadFinishTask setOnReadFinishUpdateListener(OnReadFinishUpdateListener onReadFinishUpdateListener) {
        this.onReadFinishUpdateListener = onReadFinishUpdateListener;
        return this;
    }

    public interface OnReadFinishUpdateListener {
        void onUpdate(int position);
    }

    /**
     * 删除结束的消息痕迹
     *
     * @param datas
     */
    public static void delFinishState(List<ChatTableBean> datas, boolean isStartReadFinish) {
        if (datas == null || datas.isEmpty()) {
            return;
        }
        for (Iterator<ChatTableBean> it = datas.iterator(); it.hasNext(); ) {
            ChatTableBean data = it.next();
            if (data == null) {
                continue;
            }
            if (data.getChatType() == MsgType.Read_Finish || data.getChatType() == MsgType.Del_Chat_Msg) {
                ChatTableBean.delete(data);
            } else {
                if (data.getChatUnRead() == ChatTableUnit.UNREAD || isStartReadFinish) {
                    if (data.getChatType() != MsgType.Voice) {
                        data.setChatUnRead(ChatTableUnit.READED);
                    }
                    ChatTableBean.update(data);
                }

            }
        }
        if (isAllDelMsg(datas)) {
            ChatTableBean.delete(datas);
        }
    }


    /**
     * 判断全是时间条目
     *
     * @return
     */
    public static boolean isAllDelMsg(List<ChatTableBean> list) {
        if (!list.isEmpty()) {
            for (ChatTableBean cut : list) {
                if (cut == null) {
                    continue;
                }
                if (cut.getChatType() != MsgType.History_Time) {
                    return false;
                }
            }
        }
        return true;
    }
}
